﻿CREATE TRIGGER [tr_Technician_Tracker_Insert]
ON [dbo].[t_Technician_Tracker]
FOR INSERT
AS

IF @@ROWCOUNT = 0 BEGIN
	ROLLBACK TRAN
	RAISERROR('There is no trackers to assign to Installer!',16,1)
	RETURN
END

DECLARE @MaxTrackers int
SELECT @MaxTrackers = MaxTrackers FROM t_Technician t INNER JOIN inserted i ON t.ID = i.TechnicianID
DECLARE @Count int 
SELECT @Count = COUNT(*) FROM (SELECT DISTINCT tt.TrackerID FROM t_Technician_Tracker tt INNER JOIN inserted i ON tt.TechnicianID = i.TechnicianID)T

IF @MaxTrackers = 0 OR @Count <= @MaxTrackers RETURN

ROLLBACK TRAN
RAISERROR('Tracker limit[%d]/[%d] is exeeded.',16,1,@Count,@MaxTrackers)


